#include "mainwindow.h"
#include <QMenuBar>
#include <QToolBar>
#include <QAction>
#include <QLabel>
#include <QApplication>
#include <QVBoxLayout>
#include <QWidget>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), currentLanguage("en") {
    setWindowTitle(tr("Qt Multilingual Demo"));
    resize(600, 400);

    initUI();
}

MainWindow::~MainWindow() {}

void MainWindow::initUI() {
    // 创建菜单栏
    QMenu *languageMenu = menuBar()->addMenu(tr("&Language"));

    // 语言切换菜单项
    QAction *englishAction = new QAction("English", this);
    QAction *chineseAction = new QAction("简体中文", this);
    connect(englishAction, &QAction::triggered, [this]() { changeLanguage("en_US"); });
    connect(chineseAction, &QAction::triggered, [this]() { changeLanguage("zh_CN"); });
    languageMenu->addAction(englishAction);
    languageMenu->addAction(chineseAction);

    // 创建工具栏
    QToolBar *toolbar = new QToolBar(tr("Tools"), this);
    addToolBar(Qt::TopToolBarArea, toolbar);
    toolbar->setMovable(true); // 工具栏可拖动

    // 工具栏按钮
    QAction *newToolAction = new QAction(QIcon(":/icons/new.png"), tr("New"), this);
    QAction *openToolAction = new QAction(QIcon(":/icons/open.png"), tr("Open"), this);
    toolbar->addAction(newToolAction);
    toolbar->addAction(openToolAction);

    // 主窗口内容：3 个标签
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    QVBoxLayout *layout = new QVBoxLayout(centralWidget);

    QLabel *label1 = new QLabel(tr("Label 1: Welcome"), centralWidget);
    QLabel *label2 = new QLabel(tr("Label 2: Qt Application"), centralWidget);
    QLabel *label3 = new QLabel(tr("Label 3: Multilingual Support"), centralWidget);

    label1->setAlignment(Qt::AlignCenter);
    label2->setAlignment(Qt::AlignCenter);
    label3->setAlignment(Qt::AlignCenter);

    layout->addWidget(label1);
    layout->addWidget(label2);
    layout->addWidget(label3);
}

void MainWindow::changeLanguage(const QString &lang) {
    if (lang == currentLanguage) return;

    currentLanguage = lang;
    qApp->removeTranslator(&translator);

    // 加载翻译
    if (translator.load(":/ts/RH-ALL_" + lang)) {
        qApp->installTranslator(&translator);
    }

    // 触发界面更新
    QEvent languageChangeEvent(QEvent::LanguageChange);
    QApplication::sendEvent(this, &languageChangeEvent);
}
